package com.exmaple.cdc.service;

import org.springframework.jdbc.core.JdbcTemplate;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chentao
 * @version 1.0
 * @description: TODO
 * @date 2025/3/9 上午12:18
 */
public class SysColServiceImpl implements SysColService {

    public static final String ORDINAL_POSITION = "ORDINAL_POSITION";

    public static final String COLUMN_NAME = "COLUMN_NAME";

    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /***
     * 查询表信息得到其对应信息。
     * @param schema
     * @param table
     * @return
     */
    @Override
    public List<Map<String, Object>> getCols(String schema, String table) {
        String sql = "select ORDINAL_POSITION ,COLUMN_NAME from information_schema.COLUMNS where TABLE_SCHEMA = '" + schema + "' and TABLE_NAME = '" + table + "'";
        return jdbcTemplate.queryForList(sql);
    }

    /***
     * 得到表的对应列信息
     * @param schema
     * @param table
     * @return
     */
    @Override
    public Map<Long, String> getColsMap(String schema, String table) {
        Map<Long, String> map = new HashMap<Long, String>();
        List<Map<String, Object>> cols = this.getCols(schema, table);
        for (Map<String, Object> col : cols) {
            if (col.containsKey(ORDINAL_POSITION) && col.containsKey(COLUMN_NAME)) {
                Object index = col.get(ORDINAL_POSITION);
                if (index instanceof BigInteger){
                    BigInteger bigInteger = (BigInteger)index;
                    map.put(bigInteger.longValue() -1, (String) col.get(COLUMN_NAME));
                }
                if (index instanceof Long){
                    Long longValue = (Long)index;
                    map.put(longValue -1, (String) col.get(COLUMN_NAME));
                }
            }
        }
        return map;
    }
}
